<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="Shortcut Icon" href="../images/aecc.ico" type="image/x-icon" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="../StaticFiles/element-ui/element-ui.css">
  <link rel="stylesheet" href="../StaticFiles/nprogress/nprogress.min.css">
  <link rel="stylesheet" href="../styles/vue-page-common.css">
  <script src="../Scripts/vue.min.js"></script>
  <script src="../StaticFiles/element-ui/element-ui.js"></script>
  <script src="../Scripts/axios.min.js"></script>
  <script src="../StaticFiles/nprogress/nprogress.min.js"></script>
  <script src="../Scripts/dayjs.min.js"></script>
  <script src="../Scripts/xlsx.full.min.js"></script>
  <script src="../Scripts/axios.config.js"></script>
  <script src="../Scripts/crypto-js.min.js"></script>
  <script src="../Scripts/secret.js"></script>
  <title>工步期量信息查询报表</title>
</head>

<body>
  <div id="app" v-cloak v-on:keyup.enter="getData">
    <!-- 报表标题 -->
    <vue2-report-header :title="'工步期量信息查询报表'"></vue2-report-header>
    <div style="padding: 10px;">
      <!-- 查询条件区 -->
      <el-form :inline="true" :model="queryInfo" ref="queryInfoRef" :label-position="'left'">
        <el-form-item label="组织结构:" prop="selectOrg">
          <el-cascader :options="orginazition" :props="{ checkStrictly: true}" ref="orginazitionRef"
            v-model="queryInfo.selectOrg" style="width:400px;">
          </el-cascader>
        </el-form-item>

        <el-form-item prop='productname' label="零件图号:">
          <el-autocomplete v-model.trim="queryInfo.productname" placeholder="请输入零件图号" :trigger-on-focus="false"
            style="width:240px;" :fetch-suggestions="searchProductAsync" :value-key="'productname'" :debounce="500">
          </el-autocomplete>
        </el-form-item>

        <el-form-item label="工艺版本:">
          <el-select v-model="queryInfo.selecttype" placeholder="请选择">
            <el-option :key="'最新工艺'" :label="'最新工艺'" :value="'最新工艺'"></el-option>
            <el-option :key="'默认工艺'" :label="'默认工艺'" :value="'默认工艺'"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="工艺创建时间:">
          <el-date-picker v-model="queryInfo.createdate" type="daterange" range-separator="至" value-format="yyyy-MM-dd"
            start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="getData()">查询</el-button>
          <el-button type="primary" icon="el-icon-download" size="small" @click="getExportExcel">导出</el-button>
          <el-button type="success" icon="el-icon-upload2" size="small" @click="stepCycleImport.dialogVisible = true"
            :disabled="formDisabled">导入
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 表格显示区 -->
      <el-table v-loading="loading" v-loading.fullscreen.lock="loading" :element-loading-text="loadingText"
        element-loading-background="rgba(0,0,0,0.8)" :data="dataList" stripe border>
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column label="零件信息" prop="productinfo" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column label="工艺信息" prop="workflowinfo" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column label="工序" prop="workflowstepname" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="工步id" prop="stepinfoid" width="80" show-overflow-tooltip v-if="false"></el-table-column>
        <el-table-column label="工步号" prop="stepno" width="60"></el-table-column>
        <el-table-column label="工步名称" prop="stepdesc" width="140" show-overflow-tooltip></el-table-column>
        <el-table-column label="工步版本" prop="steprev" width="75" show-overflow-tooltip></el-table-column>
        <el-table-column label="作业人数" prop="makeempcounts" width="75"></el-table-column>
        <el-table-column label="工区" prop="workcentername" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column label="班组" prop="teamname" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column label="准备工时" prop="preparecycle" width="80"></el-table-column>
        <el-table-column label="加工工时" prop="makecycle" width="80"></el-table-column>
        <el-table-column label="转运工时" prop="transfercycle" width="80"></el-table-column>
        <el-table-column label="转工周期" prop="shipcycle" width="80"></el-table-column>
        <el-table-column label="设备" prop="stepresourcelist" show-overflow-tooltip></el-table-column>
        <el-table-column label="装炉/槽量" prop="chargingqty" width="80"></el-table-column>
        <el-table-column label="工步类型" prop="steptype" width="80" show-overflow-tooltip></el-table-column>
        <el-table-column label="工艺创建时间" prop="lastchangedate" width="100" :formatter="splitDate"></el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.currentPage" :page-sizes="[14,50,100]" :page-size="queryInfo.pageSize"
        layout="prev,pager,next,jumper,sizes,total" :total="total">
      </el-pagination>

      <!-- 回到顶部 -->
      <el-backtop></el-backtop>
    </div>

    <el-dialog title="工步期量信息导入" :visible.sync="stepCycleImport.dialogVisible" width="90%" :top="'20px'"
      @close="stepCycleImport.dataList = []">
      <el-form :inline="true" ref="stepCycleImportRef">
        <el-form-item>
          <el-upload action="" :before-upload="beforeUpload" :multiple="true" accept=".xls,.xlsx">
            <el-button slot="trigger" type="primary" size="small" icon="el-icon-upload">选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="success" size="small" icon="el-icon-success" :disabled="multiple" @click="saveImportData">
            保存
          </el-button>
          <el-button type="danger" size="small" icon="el-icon-success" :disabled="multiple" @click="handleMultiDelete">
            删除
          </el-button>
        </el-form-item>
        <el-form-item>
          <span style="color:red;font-weight:bold;margin-left: 10px;">内部系统，严禁上传涉密信息</span>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="stepCycleImport.dataList" stripe border ref="stepCycleImportTable" v-loading="loading"
        v-loading.fullscreen.lock="loading" :element-loading-text="loadingText"
        element-loading-background="rgba(0,0,0,0.8)" height="640" @selection-change="handleSelectionChange">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column label="操作" width="80">
          <template slot-scope="scope">
            <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(scope.$index, scope.row)">
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="校验结果" prop="islegel" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.islegel === 1" type="success">校验成功</el-tag>
            <el-tag v-else type="danger">校验失败</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="校验失败原因" prop="illegalreason" width="300" show-overflow-tooltip>
          <template slot-scope="scope">
            <span style="color:red;font-weight:bold;" v-if="scope.row.islegel === 0">
              <i class="el-icon-warning"></i>
              {{scope.row.illegalreason}}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="工步号" width="80" prop="stepno"></el-table-column>
        <el-table-column label="工步名称" width="120" prop="stepdesc" show-overflow-tooltip></el-table-column>

        <el-table-column label="工步id" prop="stepinfoid" v-if="false"></el-table-column>
        <el-table-column label="准备工时" width="120" prop="preparecycle"></el-table-column>
        <el-table-column label="加工工时" width="120" prop="makecycle"></el-table-column>
        <el-table-column label="转运工时" width="120" prop="transfercycle"></el-table-column>
        <el-table-column label="转工周期" width="120" prop="shipcycle"></el-table-column>
        <el-table-column label="装炉/槽量" width="120" prop="chargingqty"></el-table-column>
        <el-table-column label="设备" prop="stepresourcelist"></el-table-column>
      </el-table>
    </el-dialog>
  </div>

  <script type="module">
    import { getParams, fetchSuggestion, getUserWhiteList, exportExcelData } from '../Scripts/hooks/useCommonMethod.js'
    import { getFactory, getUserInfo, getMESOrginazition } from '../Scripts/hooks/fetchAPI.js'
    import { prevWeek, thisWeek, nextWeek, prevMonth, thisMonth, nextMonth } from '../Scripts/hooks/useDateShortCut.js'
    import { splitDate } from '../Scripts/hooks/format.js'
    import Vue2ReportHeader from '../Scripts/components/Vue2ReportHeader.js'
    const app = new Vue({
      el: '#app',
      components: { Vue2ReportHeader },
      data: {
        splitDate,
        orginazition: [],
        queryInfo: {
          factoryid: '',
          selectOrg: [],// 组织结构
          productname: '',
          selecttype: '最新工艺',
          createdate: '',
          currentPage: 1,//当前页
          pageSize: 14//每页显示条数
        },
        factoryList: [],
        total: 0,
        loading: false,
        loadingText: '数据加载中...',
        dataList: [],
        pickerOptions: { shortcuts: [prevWeek, thisWeek, nextWeek, prevMonth, thisMonth, nextMonth] },
        // excel模板表头
        excelTemplateHeader: {
          stepinfoid: '工步id', preparecycle: '准备工时', makecycle: '加工工时',
          transfercycle: '转运工时', shipcycle: '转工周期', chargingqty: '装炉/槽量', stepresourcelist: '设备'
        },
        // 工步期量信息导入
        stepCycleImport: {
          dialogVisible: false,
          dataList: []
        },
        multiple: true,
        formDisabled: false
      },
      methods: {
        // 查询件号
        searchProductAsync(value, callback) {
          fetchSuggestion({ actionName: 'getProductnameAsync', name: 'productname', value, callback })
        },
        //查询数据
        async getData(currentpage) {
          // if (!this.queryInfo.createdate > 0 && this.queryInfo.selecttype === '默认工艺') {
          //   return this.$message.error('工艺创建时间不为空时，工艺版本必须选择【最新工艺】');
          // }
          this.loading = true;
          this.loadingText = '数据加载中...';
          const { data: { data, meta, total } } = await axios.post('../handler/report/RbStepCycleInfoQueryReport.ashx?action=getData', {
            type: 'getData',
            ...this.queryInfo
          })
          this.loading = false;
          if (meta.status === 500) {
            return this.$message.error(meta.msg);
          }
          this.dataList = data;
          this.total = total;
        },
        // 导出excel
        async getExportExcel() {
          // if (!this.queryInfo.createdate > 0 && this.queryInfo.selecttype === '默认工艺') {
          //   return this.$message.error('工艺创建时间不为空时，工艺版本必须选择【最新工艺】');
          // }
          const config = {
            url: '../handler/report/RbStepCycleInfoQueryReport.ashx?action=exportExcel',
            data: { type: 'exportExcel', ...this.queryInfo, factoryname: this.factoryname }
          }
          exportExcelData(config, this);
        },
        handleCurrentChange(newPage) {
          this.queryInfo.currentPage = newPage;
          this.getData();
        },
        handleSizeChange(newSize) {
          this.queryInfo.pageSize = newSize;
          this.getData();
        },
        // 文件加载后
        beforeUpload(file) {
          let reader = new FileReader();
          reader.onload = e => {
            let data = new Uint8Array(e.target.result);
            let workbook = XLSX.read(data, { type: 'array' });
            let first_sheet_name = workbook.SheetNames[0];
            let worksheet = workbook.Sheets[first_sheet_name];
            let content = XLSX.utils.sheet_to_json(worksheet, { raw: false, defval: null });
            if (content.length === 0) { return this.$message.error('所导入的excel文件为空'); }
            // 检验excel模板是否缺少列
            if (this.hasExcelMissingColumn(content[0])) { return; }
            let returnData = [];

            for (const i of content) {
              let item = {
                stepno: i["工步号"],
                stepdesc: i["工步名称"],
                stepinfoid: i["工步id"],
                preparecycle: i["准备工时"],
                makecycle: i["加工工时"],
                transfercycle: i["转运工时"],
                shipcycle: i["转工周期"],
                chargingqty: i["装炉/槽量"],
                stepresourcelist: i["设备"],
                islegel: 1,//默认校验成功
                illegalreason: '',//默认失败原因为空
              }
              returnData.push(item);
            }
            const validateData = this.validateEachRowData(returnData);
            this.stepCycleImport.dataList = validateData;
          };
          reader.readAsArrayBuffer(file);
          return false;
        },
        // 检验excel模板是否缺少列
        hasExcelMissingColumn(data) {
          return Object.values(this.excelTemplateHeader).some(i => {
            if (!(i in data)) {
              this.$message.error(`所导入的excel文件缺少【${i}】列`);
              return true;
            }
          })
        },
        // 校验所导入excel数据
        validateEachRowData(returnData) {
          let reg = /^(?!0(\.0+)?$)\d+(\.\d+)?$/;
          for (const i of returnData) {
            if (i.preparecycle && !reg.test(i.preparecycle.trim())) {
              i.islegel = 0;
              i.illegalreason = '【准备工时】必须是大于0的整数或小数';
              continue;
            }

            if (i.makecycle && !reg.test(i.makecycle.trim())) {
              i.islegel = 0;
              i.illegalreason = '【加工工时】必须是大于0的整数或小数';
              continue;
            }

            if (i.transfercycle && !reg.test(i.transfercycle.trim())) {
              i.islegel = 0;
              i.illegalreason = '【转运工时】必须是大于0的整数或小数';
              continue;
            }

            if (i.shipcycle && !reg.test(i.shipcycle.trim())) {
              i.islegel = 0;
              i.illegalreason = '【转工周期】必须是大于0的整数或小数';
              continue;
            }

            if (i.chargingqty && !reg.test(i.chargingqty.trim())) {
              i.islegel = 0;
              i.illegalreason = '【装炉/槽量】必须是大于0的整数或小数';
              continue;
            }
          }
          return returnData;
        },
        // 移除所选行
        async handleDelete(index, row) {
          const confirmResult = await this.$confirm('删除该行数据?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err)
          if (confirmResult !== 'confirm') { return this.$message.info('已取消删除!'); }
          this.stepCycleImport.dataList.splice(index, 1);
          this.$message.success('删除成功!');
        },
        // 删除多行
        async handleMultiDelete() {
          const selection = this.$refs.stepCycleImportTable.selection;
          const confirmResult = await this.$confirm('确定要删除所选的数据吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err)
          if (confirmResult !== 'confirm') { return this.$message.info('已取消删除!'); }
          const result = this.stepCycleImport.dataList.filter(item => !selection.some(otherItem => JSON.stringify(item) === JSON.stringify(otherItem)));
          this.stepCycleImport.dataList = result;
          this.$message.success('删除成功!');
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
          this.multiple = !selection.length
        },
        // 保存
        async saveImportData() {
          const selection = this.$refs.stepCycleImportTable.selection;
          if (selection.some(i => i.islegel === 0)) { return this.$message.error('存在校验失败的数据，不能保存!'); }
          const confirmResult = await this.$confirm('确定要保存吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err)
          if (confirmResult !== 'confirm') { return this.$message.info('已取消保存!'); }
          this.loading = true;
          this.loadingText = '数据加载中...';
          const { data: { data, meta, total } } = await axios.post('../handler/report/RbStepCycleInfoQueryReport.ashx?action=saveImportData', {
            type: 'saveImportData',
            willBeSavedData: selection
          })
          this.loading = false;
          if (meta.status === 500) {
            return this.$message.error(meta.msg);
          }
          this.$message.success('导入成功!');
          this.stepCycleImport.dialogVisible = false;
        },
      },
      async mounted() {
        const employeeid = getParams('uid');
        if (!employeeid) {
          this.formDisabled = true;
          return this.$notify.error({ title: '错误', message: '缺少用户信息!', duration: 0 });
        }

        // 获取用户权限白名单
        const pageurl = window.location.pathname.split('/')[3];
        const whiteList = await getUserWhiteList(pageurl, this.$message);

        if (whiteList.indexOf(employeeid) === -1) {
          this.formDisabled = true;
          return this.$notify.error({ title: '错误', message: '当前用户没有【导入】权限', duration: 0 });
        }
        this.orginazition = await getMESOrginazition({ factoryCode: '602' });
        const factoryid = Decrypt(getParams("factoryid"));
        this.factoryList = await getFactory();
        this.queryInfo.selectOrg = [factoryid];
        this.queryInfo.factoryid = factoryid;
      },
      watch: { queryInfo: { handler() { this.queryInfo.currentPage = 1 }, deep: true } }
    })
  </script>
</body>

</html>